<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
defer 2
</h1>
<p></p>
<div id="question" class="tmd-base">
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func bar() (r int) {
	defer func() {
		r += 4
		if recover() != nil {
			r += 8
		}
	}()
	
	var f func()
	defer f()
	f = func() {
		r += 2
	}

	return 1
}

func main() {
	println(bar())
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">1</label></li>
<li><label for="choiceB">7</label></li>
<li><label for="choiceC">12</label></li>
<li><label for="choiceD">13</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 13
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/DV4k3pVhS4k">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Line 12: when the call <code class="tmd-code-span">f()</code> is pushed to the defer call queue, <code class="tmd-code-span">f</code> is evaluated as nil. Calling a nil function produces a panic. But the panic doesn't happen at the push time. Instead, it will panic at the execution time later during the exiting phase of the <code class="tmd-code-span">bar()</code> call.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Line 13-15: the assignment to <code class="tmd-code-span">f</code> has not any impacts on the execution effect. In other words, this assignment is actually a no-op.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Line 4-9: a defer call could modify the named return result of its containing function (here the <code class="tmd-code-span">bar</code> function).
</div>
</li>
</ul>
<p></p>
</div>
<p></p>
</div>
